package com.henry.base.concurrency;

import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class MyQueue {
    private final LinkedList<Object> list = new LinkedList<>();
    private final AtomicInteger count = new AtomicInteger();

    private final int maxSize = 10;
    private final int minSize = 0;
    //初始化锁对象
    private Object lock = new Object();

    public void put(Object o) {
        synchronized (lock) {
            while (count.get() == maxSize) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(o);
            count.getAndIncrement();
            System.out.println("元素" + o + "被添加");
            lock.notify();
        }
    }

    public Object get() {
        synchronized (lock) {
            while (count.get() == minSize) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Object first = list.removeFirst();
            count.getAndDecrement();
            System.out.println("元素" + first + "被移除");
            lock.notify();
            return first;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyQueue myQueue = new MyQueue();
        Random random = new Random();


        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 30; i++) {
//                int num = random.nextInt(10);
//                if(num<6)
                if(i>5){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                    myQueue.put(i);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 30; i++) {
//                int num = random.nextInt(10);
//                if(num<3)
                if(i>=10){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                    myQueue.get();
            }
        });
        t2.start();
        Thread.sleep(1000);
        t1.start();
    }
}
